﻿namespace Cars.Console
{
    using Cars.Console.Common;
    using Factory;
    using Models;
    using System.Collections.Generic;
    using System.Threading;
    using System.Linq;

    public class GameEngine
    {
        private int lives = 3;
        
        private IList<Car> traffic;
        private IRenderer renderer;

        private CarFactory carfactory;

        private Player currentPlayer;

        public GameEngine(IRenderer renderer)
        {
            this.renderer = renderer;

            this.carfactory = new CarFactory();

            this.traffic = carfactory.GetCarsCollection(5).ToList();

            this.currentPlayer = new Player(new Geometry.Coordinate(Constants.FieldWidth / 2, Constants.FieldHeight - 2));
        }

        public void Run()
        {
            while (true)
            {
                this.ExecuteStep();
            }
        }

        private void ExecuteStep()
        {
            this.renderer.PrintField();

            this.RemoveExited();
            var newCar = this.carfactory.CreateTrafficCar(Randomizer.Next(1, Constants.FieldWidth - 1), 1);
            this.traffic.Add(newCar);
            this.renderer.Render(this.traffic);
            this.renderer.Render(this.currentPlayer);
            Thread.Sleep(Constants.GameSpeed);
            this.renderer.Clear();
            this.traffic.ToList().ForEach(x => x.Move());
        }

        private void RemoveExited()
        {
            var newTraffic = new List<Car>(this.traffic);
            
            newTraffic.RemoveAll(x => 
                x.Coordinates.X <= 0 || 
                x.Coordinates.X >= Constants.FieldWidth || 
                x.Coordinates.Y <= 0 || 
                x.Coordinates.Y >= Constants.FieldHeight - 1);

            this.traffic = newTraffic;
        }

    }
}
